﻿using System;
using System.Configuration;
using System.Web;
using System.IO;

namespace Shuba.Web.bulk_upload
{
    public partial class SPADA_file_upload : basePage
    {
        string msg;
        string PathServer;
        string FileName;
        string DirectoryName;
        FileInfo SPADAFileInfo;
     
        private bool CreateFolder(ref string err)
        {
            bool status = false;
            try
            {
                string path = Server.MapPath("~/spada_file_version/");

                DirectoryName = string.Format("{0:MMMM-dd-yyyy HH:mm:ss}", ProcessingDate()).Replace(":", "").Replace(" ","");
                PathServer = path + DirectoryName;
                Directory.CreateDirectory(PathServer);
                if (Directory.Exists(PathServer)) status = true;
            }
            catch (Exception ex)
            {
                err = ex.Message;
                lblStatus.Visible = true;
                lblStatus.Text = ex.Message;
            }
            return status;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_SPADA_FILE_VERSION");

                if (!IsUserAdd(acl))
                {
                    msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }
                LabelTitle.Text = GetPageTitle("MSTR_SPADA_FILE_VERSION");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            string err = "";
            if (CreateFolder(ref err))
            {
                Int16 berhasil, gagal, hitung;
                berhasil = 0;
                gagal = 0;
                hitung = 1;

                Shuba.Business.SPADAFile _SPADAFile = new Shuba.Business.SPADAFile();
                
                bool alreadyNameFile = false;

                if (_SPADAFile.getVersion(txtVersion.Text.Trim()) > 0)
                {
                    msg = "Not allowed to upload the same name of file";
                    Alert(msg);
                }

                for (Int16 icount = 1; icount <= Request.Files.Count; icount++)
                {
                    string nameFile = "";
                    if (Request.Files.Get(icount - 1).FileName.ToString() != "")
                    {
                        string fileName = Request.Files.Get(icount - 1).FileName.ToString();
                        nameFile = fileName.Split('\\')[fileName.Split('\\').Length - 1];

                        int sameFile = 0;
                        for (Int16 icount2 = 1; icount2 <= Request.Files.Count; icount2++)
                        {
                            if (Request.Files.Get(icount2 - 1).FileName.ToString() != "")
                            {
                                string fileName2 = Request.Files.Get(icount2 - 1).FileName.ToString();
                                string nameFile2 = fileName2.Split('\\')[fileName2.Split('\\').Length - 1];

                                if (nameFile == nameFile2)
                                {
                                    sameFile++;
                                    if (sameFile > 1) alreadyNameFile = true;
                                }
                            }
                        }
                    }
                }

                if (alreadyNameFile)
                {
                    msg = "Not allowed to upload the same name of file";
                    Alert(msg);
                }
                else
                {
                    for (Int16 icount = 1; icount <= Request.Files.Count; icount++)
                    {
                        if (Request.Files.Get(icount - 1).FileName.ToString() != "")
                        {
                            FileName = Path.GetFileName(Request.Files.Get(icount - 1).FileName.ToString());
                            FileInfo fileAsli = new FileInfo(Request.Files.Get(icount - 1).FileName);

                            Request.Files.Get(icount - 1).SaveAs(PathServer + "\\" + FileName + "~" + hitung);
                            System.Threading.Thread.Sleep(1000);

                            //SPADAFileInfo = new FileInfo(Request.Files.Get(icount - 1).FileName.ToString() + "~" + hitung);
                            SPADAFileInfo = new FileInfo(PathServer + "\\" + FileName + "~" + hitung);

                            Shuba.Business.SPADAFile list = new Shuba.Business.SPADAFile();
                            //Shuba.Model.SPADAFileInfo bi = new Shuba.Model.SPADAFileInfo();
                            
                            string cheksum = list.CalculateCheksum(PathServer + "\\" + FileName + "~" + hitung);

                            //bi = list.GetDateSystem();
                            var info = new Shuba.Model.SPADAFileInfo();
                            info.DATE_FILE_UPLOAD = ProcessingDate(); //bi.GETDATE,
                            info.DATE_FILE_MODIFIED = DateTime.Now.AddDays(-2); //fileAsli.LastWriteTime;//ntar jangan lupa diganti
                            info.FILE_SIZE_UPLOAD = SPADAFileInfo.Length;
                            info.PATH_FILE_UPLOAD = PathServer;
                            info.NAME_FOLDER_UPLOAD = DirectoryName;
                            info.FILE_NAME_UPLOAD = SPADAFileInfo.Name; //+ "~" + hitung ,
                            info.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                            info.ENTRY_DATE = ProcessingDate();
                            info.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                            info.UPDATE_DATE = ProcessingDate();
                            info.ACT_TYPE = "UPLOAD";
                            info.VERSION = txtVersion.Text;
                            info.CHECKSUM = Convert.ToInt64(cheksum);

                            if (_SPADAFile.Save2(info) > 0)
                            {
                                berhasil++;
                                hitung++;
                            }
                            else
                            {
                                gagal++;
                            }                            
                        }
                        else
                        {
                            gagal++;
                        }
                    }
                    msg = "Upload Notification \\n Succesfully Upload : " + berhasil + " Record(s)\\n\\nFailed to Upload : " + gagal + " Record(s)";
                    AlertAndRedirect(msg, "SPADA_file_list.aspx");
                }
            }
            else
            {
                Alert("Failed create folder spada file to stored data :\\n " + err + "");
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("SPADA_file_list.aspx");
        }
    }
}
